package cn.jszx.core.controller;

import cn.jszx.core.bean.user.User;
import cn.jszx.core.service.user.UserService;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by karakapi on 15-9-16.
 */
@Controller//控制器必须注解
@RequestMapping(value = "/debug")
@Scope("singleton")//单例
public class TestContoller {
    private static Logger logger = LoggerFactory.getLogger(TestContoller.class);
    //禁止新建变量
    @Autowired
    private UserService testService;

    //主页
    @RequestMapping(value = "/index")
    public String index() {
        logger.debug("=> indexPage");
        return "test/test_main";
    }

    @RequestMapping(value = "/loginPage")
    public String loginPage() {
        logger.debug("=> loginPage");
        return "index";
    }

    @RequestMapping(value = "/login")
    public String login(User user) {
        logger.debug(user.toString());
        testService.addUser(user);


        return "index";
    }

    @RequestMapping(value = "/ajax")
    public void ajax(HttpServletResponse response) throws Exception {
        List<String> body = new LinkedList<String>();
        body.add("hello");
        body.add("hi");

        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(writer, body);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        out.print(writer.toString());
        logger.debug("=> " + writer.toString());
    }

}
